/**
 * File:		ServerSocket.java
 * Project:		Virtual Advisor
 * Module:		ServerSocket
 * Author:		Rotem Ganel
 * Created:		Apr 24, 2011
 * Updated:		Apr 24, 2011
 * Version:		1 (in progress)
 * 
 * Adapted from Oracle Java Socket Tutorial
 * http://www.oracle.com/technetwork/java/socket-140484.html#server
 */
package server.serverApp;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.*;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import clientApp.VirtualAdvisor;
import clientSocket.Request;
import clientSocket.RequestInterpreter;

class ServerPortal implements Runnable {
	  private Socket client;
	  
	  ServerPortal(Socket client) {
		  this.client = client;
	  }

	  public void run() {
		  ObjectOutputStream serializer = null;
		  ObjectInputStream unpacker = null;
		  
		  try {
			  serializer = new ObjectOutputStream(client.getOutputStream());
			  unpacker = new ObjectInputStream(client.getInputStream());
		  } catch (Exception e) {
			  e.printStackTrace();
		  }

	      while(true) {
	    	  try {
		    	  //Receive request
	    		  Request request = (Request)unpacker.readObject();
	    		  
	    		  //Respond to request
	    		  Object response = RequestHandler.handle(request);
	    		  serializer.writeObject(response);
	    	  } catch (SocketException e) {
	    		  System.out.println("Connection error.");
	    		  System.exit(-1);
	    	  } catch (EOFException e) {
//	    		  System.out.println("Client has disconnected.");
//	    		  System.exit(-1);
	    	  } catch (Exception e) {
	    		  e.printStackTrace();
	    	  }
	      }
	  }
}
